<!-- V-admin/src/views/video/VideoView.vue -->
<template>
  <div class="video-container">
    <div class="video-header">
      <h1>视频管理</h1>
      <div class="header-actions">
        <el-button type="primary" :icon="Plus" @click="createVideo">
          上传视频
        </el-button>
      </div>
    </div>

    <!-- 筛选条件 -->
    <el-card class="filter-card">
      <el-form :model="filterForm" inline>
        <el-form-item label="搜索视频">
          <el-input
            v-model="filterForm.search"
            placeholder="请输入视频标题或描述"
            clearable
            style="width: 200px"
            @clear="handleSearch"
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button :icon="Search" @click="handleSearch" />
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="全部" clearable @change="handleSearch">
            <el-option label="公开" :value="1" />
            <el-option label="私密" :value="2" />
            <el-option label="删除" :value="0" />
          </el-select>
        </el-form-item>

        <el-form-item label="分类">
          <el-select v-model="filterForm.category" placeholder="全部分类" clearable @change="handleSearch">
            <el-option 
              v-for="category in categories" 
              :key="category" 
              :label="category" 
              :value="category" 
            />
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据统计卡片 -->
    <el-row :gutter="20" class="stats-cards">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon total">
              <el-icon><VideoCamera /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statsData.totalVideos || 0 }}</div>
              <div class="stat-label">总视频数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon public">
              <el-icon><View /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ getStatusCount(1) }}</div>
              <div class="stat-label">公开视频</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon views">
              <el-icon><Monitor /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statsData.totalViews || 0 }}</div>
              <div class="stat-label">总播放量</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon categories">
              <el-icon><Collection /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ categories.length }}</div>
              <div class="stat-label">分类数量</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 视频列表 -->
    <el-card class="video-list-card">
      <template #header>
        <span>视频列表</span>
        <el-button type="primary" text @click="loadVideos">刷新</el-button>
      </template>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>

      <!-- 数据内容 -->
      <div v-else>
        <el-table :data="videoList" style="width: 100%" v-loading="tableLoading">
          <el-table-column prop="cover_image" label="封面" width="100">
            <template #default="scope">
              <div class="video-cover">
                <el-image 
                  v-if="scope.row.cover_image" 
                  :src="scope.row.cover_image" 
                  :preview-src-list="[scope.row.cover_image]"
                  fit="cover"
                  style="width: 80px; height: 60px; border-radius: 4px;"
                >
                  <template #error>
                    <div class="image-slot">
                      <el-icon><Picture /></el-icon>
                    </div>
                  </template>
                </el-image>
                <div v-else class="cover-placeholder">
                  <el-icon><VideoCamera /></el-icon>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="video_title" label="视频信息" min-width="200">
            <template #default="scope">
              <div class="video-info">
                <div class="video-title">{{ scope.row.video_title }}</div>
                <div class="video-desc">{{ scope.row.video_description || '暂无描述' }}</div>
                <div class="video-meta">
                  <span class="category">{{ scope.row.category || '未分类' }}</span>
                  <span class="views">播放: {{ scope.row.video_click_count || 0 }}</span>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="anchor.anchor_name" label="主播" width="120">
            <template #default="scope">
              {{ scope.row.anchor?.anchor_name || '未知主播' }}
            </template>
          </el-table-column>

          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="created_at" label="创建时间" width="150">
            <template #default="scope">
              {{ formatDate(scope.row.created_at) }}
            </template>
          </el-table-column>

          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button type="primary" link @click="viewVideoDetail(scope.row)">
                详情
              </el-button>
              <el-button type="warning" link @click="editVideo(scope.row)">
                编辑
              </el-button>
              <el-button type="danger" link @click="deleteVideo(scope.row.video_id)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.pageSize"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 创建/编辑视频对话框 -->
    <el-dialog
      v-model="showEditDialog"
      :title="editMode === 'create' ? '上传视频' : '编辑视频'"
      width="600px"
    >
      <el-form :model="videoForm" :rules="videoRules" ref="videoFormRef" label-width="80px">
        <el-form-item label="视频标题" prop="video_title">
          <el-input v-model="videoForm.video_title" placeholder="请输入视频标题" />
        </el-form-item>

        <el-form-item label="视频描述">
          <el-input 
            v-model="videoForm.video_description" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入视频描述" 
          />
        </el-form-item>

        <el-form-item label="分类">
          <el-select v-model="videoForm.category" placeholder="选择分类" clearable style="width: 100%">
            <el-option 
              v-for="category in categories" 
              :key="category" 
              :label="category" 
              :value="category" 
            />
            <el-option label="添加新分类" value="__new__">
              <div class="custom-category-option">
                <el-input 
                  v-if="showNewCategoryInput" 
                  v-model="newCategory" 
                  placeholder="输入新分类"
                  @blur="addNewCategory"
                  @keyup.enter="addNewCategory"
                />
                <span v-else @click="showNewCategoryInput = true">+ 添加新分类</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="状态">
          <el-radio-group v-model="videoForm.status">
            <el-radio :label="1">公开</el-radio>
            <el-radio :label="2">私密</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="editMode === 'edit'" label="视频文件">
          <el-upload
            class="video-upload"
            :action="`${baseURL}/admin/videos/${currentVideoId}/upload`"
            :headers="uploadHeaders"
            :on-success="handleVideoUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeVideoUpload"
          >
            <el-button type="primary">重新上传视频</el-button>
            <template #tip>
              <div class="el-upload__tip">支持 mp4, avi, mov 等视频格式，大小不超过 100MB</div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="封面图片">
          <el-upload
            class="cover-upload"
            :action="editMode === 'create' ? '' : `${baseURL}/admin/videos/${currentVideoId}/cover`"
            :headers="uploadHeaders"
            :on-success="handleCoverUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeCoverUpload"
            :show-file-list="false"
          >
            <el-image 
              v-if="videoForm.cover_image" 
              :src="videoForm.cover_image" 
              fit="cover"
              style="width: 120px; height: 90px; border-radius: 4px;"
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <div v-else class="upload-area">
              <el-icon><Plus /></el-icon>
              <div>上传封面</div>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button type="primary" @click="submitVideoForm" :loading="submitting">
          {{ editMode === 'create' ? '创建' : '更新' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'  // 修复：添加 watch 导入
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Search,
  VideoCamera,
  View,
  Monitor,
  Collection,
  Picture
} from '@element-plus/icons-vue'
import { adminAPI } from '../../api/admin'

// 响应式数据
const loading = ref(true)
const tableLoading = ref(false)
const showEditDialog = ref(false)
const submitting = ref(false)
const showNewCategoryInput = ref(false)
const newCategory = ref('')

const editMode = ref<'create' | 'edit'>('create')
const currentVideoId = ref<number | null>(null)

// 筛选表单
const filterForm = ref({
  search: '',
  status: '',
  category: ''
})

// 分页数据
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0
})

// 视频表单
const videoForm = ref({
  video_title: '',
  video_description: '',
  category: '',
  status: 1,
  cover_image: ''
})

const videoFormRef = ref()

const videoRules = {
  video_title: [
    { required: true, message: '请输入视频标题', trigger: 'blur' }
  ]
}

// 数据存储
const videoList = ref<any[]>([])
const statsData = ref<any>({})
const categories = ref<string[]>([])

// 计算属性
const baseURL = computed(() => import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000/api')

const uploadHeaders = computed(() => {
  const token = localStorage.getItem('token')
  return {
    Authorization: `Bearer ${token}`
  }
})

const getStatusCount = (status: number) => {
  const statusData = statsData.value.statusStats?.find((item: any) => item.status === status)
  return statusData?.count || 0
}

// 方法
const loadVideos = async () => {
  try {
    tableLoading.value = true
    console.log('🎬 加载视频列表...')

    const params = {
      page: pagination.value.current,
      limit: pagination.value.pageSize,
      search: filterForm.value.search,
      status: filterForm.value.status,
      category: filterForm.value.category
    }

    const response = await adminAPI.getVideos(params)
    
    if (response.success) {
      videoList.value = response.data.videos
      pagination.value.total = response.data.pagination.total
      console.log('✅ 视频列表加载成功:', videoList.value.length)
    } else {
      throw new Error(response.message)
    }
  } catch (error: any) {
    console.error('❌ 加载视频列表失败:', error)
    ElMessage.error('加载视频列表失败: ' + (error.message || '网络错误'))
    
    // 使用模拟数据
    videoList.value = generateMockVideos()
    pagination.value.total = videoList.value.length
  } finally {
    tableLoading.value = false
    loading.value = false
  }
}

const loadVideoStats = async () => {
  try {
    console.log('📊 加载视频统计...')
    const response = await adminAPI.getVideoStats()
    
    if (response.success) {
      statsData.value = response.data
      // 提取分类
      if (statsData.value.categoryStats) {
        categories.value = statsData.value.categoryStats.map((item: any) => item.category)
      }
      console.log('✅ 视频统计加载成功')
    } else {
      throw new Error(response.message)
    }
  } catch (error: any) {
    console.error('❌ 加载视频统计失败:', error)
    // 使用模拟统计
    statsData.value = {
      totalVideos: 28,
      totalViews: 15600,
      statusStats: [
        { status: 1, count: 20 },
        { status: 2, count: 5 },
        { status: 0, count: 3 }
      ],
      categoryStats: [
        { category: '音乐', count: 8 },
        { category: '舞蹈', count: 6 },
        { category: '生活', count: 4 }
      ]
    }
    categories.value = ['音乐', '舞蹈', '生活', '游戏', '教学']
  }
}

const handleSearch = () => {
  pagination.value.current = 1
  loadVideos()
}

const handleSizeChange = (newSize: number) => {
  pagination.value.pageSize = newSize
  pagination.value.current = 1
  loadVideos()
}

const handleCurrentChange = (newPage: number) => {
  pagination.value.current = newPage
  loadVideos()
}

const createVideo = () => {
  editMode.value = 'create'
  videoForm.value = {
    video_title: '',
    video_description: '',
    category: '',
    status: 1,
    cover_image: ''
  }
  showEditDialog.value = true
}

const editVideo = (video: any) => {
  editMode.value = 'edit'
  currentVideoId.value = video.video_id
  videoForm.value = {
    video_title: video.video_title,
    video_description: video.video_description || '',
    category: video.category || '',
    status: video.status,
    cover_image: video.cover_image || ''
  }
  showEditDialog.value = true
}

const submitVideoForm = async () => {
  try {
    if (!videoFormRef.value) return
    
    await videoFormRef.value.validate()
    submitting.value = true

    if (editMode.value === 'create') {
      const response = await adminAPI.createVideo(videoForm.value)
      if (response.success) {
        ElMessage.success('视频创建成功')
        showEditDialog.value = false
        loadVideos()
      } else {
        throw new Error(response.message)
      }
    } else {
      if (!currentVideoId.value) return
      const response = await adminAPI.updateVideo(currentVideoId.value, videoForm.value)
      if (response.success) {
        ElMessage.success('视频更新成功')
        showEditDialog.value = false
        loadVideos()
      } else {
        throw new Error(response.message)
      }
    }
  } catch (error: any) {
    console.error('提交视频表单失败:', error)
    ElMessage.error('操作失败: ' + (error.message || '网络错误'))
  } finally {
    submitting.value = false
  }
}

const deleteVideo = async (videoId: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这个视频吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await adminAPI.deleteVideo(videoId)
    if (response.success) {
      ElMessage.success('视频删除成功')
      loadVideos()
    } else {
      throw new Error(response.message)
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除视频失败:', error)
      ElMessage.error('删除失败: ' + (error.message || '网络错误'))
    }
  }
}

const viewVideoDetail = (video: any) => {
  ElMessage.info(`查看视频详情: ${video.video_title}`)
  // 实际项目中这里可以跳转到详情页面或打开详情对话框
}

const addNewCategory = () => {
  if (newCategory.value.trim()) {
    if (!categories.value.includes(newCategory.value)) {
      categories.value.push(newCategory.value)
    }
    videoForm.value.category = newCategory.value
    newCategory.value = ''
  }
  showNewCategoryInput.value = false
}

const beforeVideoUpload = (file: File) => {
  const isVideo = file.type.startsWith('video/')
  const isLt100M = file.size / 1024 / 1024 < 100

  if (!isVideo) {
    ElMessage.error('只能上传视频文件!')
    return false
  }
  if (!isLt100M) {
    ElMessage.error('视频大小不能超过 100MB!')
    return false
  }
  return true
}

const beforeCoverUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  return true
}

const handleVideoUploadSuccess = (response: any) => {
  if (response.success) {
    ElMessage.success('视频文件上传成功')
  } else {
    ElMessage.error(response.message || '上传失败')
  }
}

const handleCoverUploadSuccess = (response: any) => {
  if (response.success) {
    ElMessage.success('封面图片上传成功')
    if (response.data?.cover_image) {
      videoForm.value.cover_image = response.data.cover_image
    }
  } else {
    ElMessage.error(response.message || '上传失败')
  }
}

const handleUploadError = (error: any) => {
  console.error('上传失败:', error)
  ElMessage.error('文件上传失败')
}

// 工具函数
const getStatusType = (status: number) => {
  const statusMap: { [key: number]: string } = {
    1: 'success', // 公开
    2: 'warning', // 私密
    0: 'danger'   // 删除
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status: number) => {
  const statusMap: { [key: number]: string } = {
    1: '公开',
    2: '私密', 
    0: '删除'
  }
  return statusMap[status] || '未知'
}

const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 模拟数据生成
const generateMockVideos = () => {
  return Array.from({ length: 10 }, (_, index) => ({
    video_id: index + 1,
    video_title: `示例视频 ${index + 1}`,
    video_description: `这是第 ${index + 1} 个示例视频的描述内容`,
    video_url: '',
    cover_image: '',
    video_click_count: Math.floor(Math.random() * 1000),
    category: ['音乐', '舞蹈', '生活', '游戏'][index % 4],
    status: [1, 1, 1, 2, 0][index % 5],
    created_at: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
    anchor: {
      anchor_name: `主播${(index % 3) + 1}`,
      avatar: ''
    }
  }))
}

// 组件挂载
onMounted(() => {
  Promise.all([loadVideos(), loadVideoStats()])
})

// 移除不必要的 watch，简化代码
</script>

<style scoped>
.video-container {
  padding: 20px;
}

.video-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  height: 100px;
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: white;
}

.stat-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.public {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.views {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.categories {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.video-list-card {
  margin-bottom: 20px;
}

.video-cover {
  display: flex;
  justify-content: center;
  align-items: center;
}

.cover-placeholder {
  width: 80px;
  height: 60px;
  background: #f5f7fa;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #c0c4cc;
}

.video-info {
  padding: 4px 0;
}

.video-title {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
  line-height: 1.4;
}

.video-desc {
  font-size: 12px;
  color: #909399;
  margin-bottom: 6px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.video-meta {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: #606266;
}

.video-meta .category {
  background: #f0f9ff;
  color: #409eff;
  padding: 2px 6px;
  border-radius: 3px;
}

.video-meta .views {
  color: #67c23a;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.loading-container {
  margin-top: 20px;
}

.custom-category-option {
  width: 100%;
}

.upload-area {
  width: 120px;
  height: 90px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #8c939d;
  cursor: pointer;
  transition: border-color 0.3s;
}

.upload-area:hover {
  border-color: #409eff;
}

.image-slot {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  color: #909399;
}
</style>